package com.creditease.tmsp.modules.sys.security;


import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.creditease.tmsp.common.config.Global;
import com.creditease.tmsp.modules.sys.security.SystemAuthorizingRealm.Principal;


/**
 * 
 * @Description：用户权限控制过滤自定义Frame 
 * @author：
 * @CreateDate：
 * @Company:
 * @version 
 */
@Component("frameperms")

public class FramePermissionsAuthorizationFilter extends

		PermissionsAuthorizationFilter {
	public Logger logger = LoggerFactory.getLogger(getClass());
	

	@Override

	public boolean isAccessAllowed(ServletRequest request,

			ServletResponse response, Object mappedValue) throws IOException {
		

		HttpServletRequest req = (HttpServletRequest) request;

		Subject subject = getSubject(request, response);
		Principal shiroUser = (Principal) subject.getPrincipal();

		String originalUri = req.getRequestURI();
		String uri = originalUri;

		String contextPath = req.getContextPath();

		int i=uri.indexOf(contextPath);
		//去除项目路径

		if(i>-1){

			uri=uri.substring(i+contextPath.length());			

		}
        //去除后台和前台访问的路径
		String adminPath = Global.getAdminPath();
		String frontPath = Global.getFrontPath();
		if(uri.startsWith(adminPath)){
			uri = uri.substring(adminPath.length());
		}else if(uri.startsWith(frontPath)){
			uri = uri.substring(frontPath.length());
		}
		//去除路径最后的"/"防止通配出错
		if(uri.endsWith("/")&&!uri.equals("/")){
			uri = uri.substring(0,uri.length()-1);
		}
		//去除路径中";"
		if(uri.indexOf(";")>-1){
			uri = uri.split(";")[0];
		}
		//去除路径中多个"/"
		while(uri.indexOf("//")>-1){
			uri = uri.replaceAll("//", "/");
		}
		if(uri.endsWith("form")){
			uri = uri.substring(0,uri.length()-5);
		}
		//增删改权限统一为"编辑"权限
		if(uri.endsWith("delete")){
			uri = uri.substring(0,uri.length()-6)+"save";
		}
		//去除路径结尾的form,form在本系统中担任view,edit,save的角色
		//权限拦截,不拦截项目根路径,不拦截超级管理员
	    boolean permitted = false;
		if(StringUtils.isBlank(uri)||"/".equals(uri)||"1".equals(shiroUser.getId())){
			permitted = true;
		}else{
		    permitted = subject.isPermitted(uri);
		}
		
		//记录访问日志，及其拦截情况
        StringBuilder sb = new StringBuilder();
        sb.append("权限拦截:");
        sb.append(originalUri);
        sb.append("；用户:");
        sb.append(shiroUser.getLoginName());
        sb.append("；访问状态：");
        sb.append(permitted?"通过":"未通过");
		logger.info(sb.toString());
		

		return permitted;



	}

}

